package com.docMan.lucene;

import java.io.IOException;
import java.io.StringReader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.queryparser.xml.builders.BooleanQueryBuilder;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.BooleanQuery.Builder;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.SortField.Type;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopFieldCollector;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.search.highlight.Fragmenter;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.QueryBuilder;
import org.apache.struts2.convention.StringTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.docMan.bean.IndexFile;
import com.docMan.bean.PageLucene;
import com.docMan.dao.pojo.DocFile;
import com.docMan.utils.CastUtil;
import com.docMan.utils.FinalConfig;

public class Searcher {
	private Directory indexDir;
	private IndexReader reader;
	private IndexSearcher is;
	private HttpSession session;


	public Searcher(String path ,HttpSession session) throws IOException {
		indexDir = FSDirectory.open(Paths.get(path));
		reader = DirectoryReader.open(indexDir);
		is = new IndexSearcher(reader);
		this.session=session;
	}
	public Searcher(String path ) throws IOException {
		indexDir = FSDirectory.open(Paths.get(path));
		reader = DirectoryReader.open(indexDir);
		is = new IndexSearcher(reader);
	}

	/**
	 * 对于write
	 * 
	 * @throws IOException
	 */
	public void reopen() throws IOException {
		IndexReader newReader = DirectoryReader
				.openIfChanged((DirectoryReader) reader);
		if (newReader != null) {
			reader = newReader;
			is = new IndexSearcher(reader);
		}

	}

	public Document getDocument(ScoreDoc scoreDoc) throws IOException {

		return is.doc(scoreDoc.doc);
	}

	/**
	 * 对 索引指定的字段 fileName 进行
	 * 
	 * @param fileName
	 * @return
	 * @throws IOException
	 */
	public TopDocs TermQueryL(String fieldName, String fileName)
			throws IOException {
		Term term = new Term(fieldName, fileName);
		TermQuery termQuery = new TermQuery(term);
		TopDocs hits = is.search(termQuery, 10);
		return hits;
	}

	/**
	 * 还需要重构， 对多域进行搜索，可以指定and 和or以及字段
	 * 
	 * @param termMaps
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public TopDocs TermsQueryL(Map<String, String> termMaps)
			throws ParseException, IOException {
		String[] fields = new String[termMaps.size()];
		String[] params = new String[termMaps.size()];
		BooleanClause.Occur[] flags = new BooleanClause.Occur[termMaps.size()];
		int i = 0;
		for (String field : termMaps.keySet()) {
			fields[i] = field;
			params[i] = termMaps.get(field);
			flags[i] = BooleanClause.Occur.MUST;
			i++;
		}
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		Query query = MultiFieldQueryParser.parse(params, fields, flags,
				analyzer);
		TopDocs hits = is.search(query, 10);
		return hits;
	}

	public TopDocs queryParse(String fieldName, String text)
			throws IOException, ParseException {
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		QueryParser parser = new QueryParser(fieldName, analyzer);
		Query query = parser.parse(text);
		TopDocs hits = is.search(query, 10);
		return hits;
	}

	/**
	 * 多域，多条件的联合查询
	 * 
	 * @param fieldName
	 * @param text
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws InvalidTokenOffsetsException
	 */
	public List<IndexFile> searchHighlighter(String fieldName, String text)
			throws ParseException, IOException, InvalidTokenOffsetsException {
		List<IndexFile> docFiles = new ArrayList<IndexFile>();
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		String[] fields = new String[] { "fileName", "content" };
		BooleanClause.Occur[] flags = new BooleanClause.Occur[] {
				BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
		Query query = MultiFieldQueryParser
				.parse(text, fields, flags, analyzer);
		TopDocs hits = is.search(query, 10);
		QueryScorer scorer = new QueryScorer(query);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				"<b><font color='red'>", "</font></b>");
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = is.doc(scoreDoc.doc);
			IndexFile docFile = new IndexFile();
			docFile.setFileId(doc.get("id"));
			docFile.setHumanName(doc.get("humanName"));
			docFile.setFilePath(doc.get("path"));
			docFile.setCreateTime(doc.get("createTime"));
			docFile.setImageCssClass(doc.get("imageCssClass"));
			String fileName = doc.get(fieldName);
			String content = doc.get("content");
			if (fileName != null) {
				TokenStream tokenStream = analyzer.tokenStream(fieldName,
						new StringReader(fileName));
				String highlighterFilename = highlighter.getBestFragment(
						tokenStream, fileName);
				if (null == highlighterFilename) {
					docFile.setFileName(fileName);
				} else {
					docFile.setFileName(highlighterFilename);
				}
			}
			if (content != null) {
				TokenStream tokenStream = analyzer.tokenStream("content",
						new StringReader(content));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, content);
				docFile.setContent(highlighterContent);
			}
			docFiles.add(docFile);
		}
		return docFiles;
	}

	/**
	 * 高亮搜索的分页查询
	 * 
	 * @param pageLucene
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 * @throws InvalidTokenOffsetsException
	 */
	public PageLucene searchHighlighter(PageLucene pageLucene)
			throws ParseException, IOException, InvalidTokenOffsetsException {
		List<IndexFile> docFiles = new ArrayList<IndexFile>();
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		String[] fields = new String[] { "fileName", "content" };
		BooleanClause.Occur[] flags = new BooleanClause.Occur[] {
				BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
		Query query = MultiFieldQueryParser.parse(pageLucene.getSearchText(),
				fields, flags, analyzer);
		Sort sort = new Sort(new SortField("fileName", Type.SCORE),
				new SortField("content", Type.SCORE));
		TopFieldCollector topFieldCollector = TopFieldCollector.create(sort,
				pageLucene.getCurrentPage() * pageLucene.getEveryPage(), false,
				false, false);
		is.search(query, topFieldCollector);
		TopDocs hits = topFieldCollector.topDocs(
				(pageLucene.getCurrentPage() - 1) * pageLucene.getEveryPage(),
				pageLucene.getCurrentPage() * pageLucene.getEveryPage());
		QueryScorer scorer = new QueryScorer(query);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				"<b><font color='red'>", "</font></b>");
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = is.doc(scoreDoc.doc);
			IndexFile docFile = doc2IndexFile(doc);
			String fileName = doc.get("fileName");
			String content = doc.get("content");
			if (fileName != null) {
				TokenStream tokenStream = analyzer.tokenStream("fieldName",
						new StringReader(fileName));
				String highlighterFilename = highlighter.getBestFragment(
						tokenStream, fileName);
				if (null == highlighterFilename) {
					docFile.setFileName(fileName);
				} else {
					docFile.setFileName(highlighterFilename);
				}
			}
			if (content != null) {
				TokenStream tokenStream = analyzer.tokenStream("content",
						new StringReader(content));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, content);
				docFile.setContent(highlighterContent);
			}
			docFiles.add(docFile);

		}
		pageLucene.setTotalCount(topFieldCollector.getTotalHits());
		pageLucene.setResults(docFiles);
		pageLucene.initPageLucene();
		return pageLucene;
	}

	public PageLucene pageBooleanSearch(PageLucene pageLucene)
			throws ParseException, IOException, InvalidTokenOffsetsException {
		BooleanQuery booleanQuery = new BooleanQuery();
		List<IndexFile> docFiles = new ArrayList<IndexFile>();
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		String[] fields = new String[] { "fileName", "content" };
		BooleanClause.Occur[] flags = new BooleanClause.Occur[] {
				BooleanClause.Occur.SHOULD, BooleanClause.Occur.SHOULD };
		Query query = MultiFieldQueryParser.parse(pageLucene.getSearchText(),
				fields, flags, analyzer);
		if (!pageLucene.getIndexFrom().equals(FinalConfig.INDEX_FROM_ALL)) {
			Term term = new Term("indexFrom", pageLucene.getIndexFrom());
			Query termQuery = new TermQuery(term);
			booleanQuery.add(termQuery, Occur.MUST);
		}
		// 判断是否是需要在时间范围内查询，需要时间范围查询的话就需要使用组合查询BooleanQuery
		if (pageLucene.isBooleanQuery()) {
			NumericRangeQuery<Long> rangeQuery = NumericRangeQuery
					.newLongRange("date", pageLucene.getStartDate().getTime(),
							pageLucene.getEndDate().getTime(), true, true);
			booleanQuery.add(rangeQuery, Occur.MUST);
		}
		// 设置搜索文件的过滤，过滤掉不可搜索的文件
		booleanQuery = setSearchAble(booleanQuery);

		/*
		 * Sort sort = new Sort(new SortField("fileName", Type.SCORE), new
		 * SortField("content", Type.SCORE), new SortField("swbh", Type.SCORE),
		 * new SortField("lwbh", Type.SCORE));
		 */
		Sort sort = Sort.RELEVANCE;
		TopFieldCollector topFieldCollector = TopFieldCollector.create(sort,
				pageLucene.getCurrentPage() * pageLucene.getEveryPage(), false,
				false, false);
		// if (pageLucene.isBooleanQuery()) {
		is.search(booleanQuery, topFieldCollector);
		/*
		 * } else { is.search(query, topFieldCollector); }
		 */
		TopDocs hits = topFieldCollector.topDocs(
				(pageLucene.getCurrentPage() - 1) * pageLucene.getEveryPage(),
				pageLucene.getCurrentPage() * pageLucene.getEveryPage());
		QueryScorer scorer = new QueryScorer(query);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				"<b><font color='red'>", "</font></b>");
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = is.doc(scoreDoc.doc);
			IndexFile docFile = doc2IndexFile(doc);
			String fileName = doc.get("fileName");
			String content = doc.get("content");
			// System.out.println(pageLucene.getIndexFrom()+"_"+doc.get("indexFrom"));
			if (fileName != null) {
				TokenStream tokenStream = analyzer.tokenStream("fieldName",
						new StringReader(fileName));
				String highlighterFilename = highlighter.getBestFragment(
						tokenStream, fileName);
				if (null == highlighterFilename) {
					docFile.setFileName(fileName);
				} else {
					docFile.setFileName(highlighterFilename);
				}
			}
			if (content != null) {
				TokenStream tokenStream = analyzer.tokenStream("content",
						new StringReader(content));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, content);
				docFile.setContent(highlighterContent);
			}
			docFiles.add(docFile);

		}
		pageLucene.setTotalCount(topFieldCollector.getTotalHits());
		pageLucene.setResults(docFiles);
		pageLucene.initPageLucene();
		return pageLucene;
	}

	/**
	 * 这个方法主要是设置搜索是的可搜索范围的过滤，根据文件索引的范围进行过滤，主要是三个字段 searchable ，unitId,
	 * humanIds这三个字段来过滤 searchable
	 * 0表示全部可搜索,-1表示不可搜索，1表示搜索用户是该部门的可以搜索,根据unitId来过滤，2表示自定义额度，根据humanIds的字段来过滤
	 * 
	 * @param booleanQuery
	 * @return
	 * @throws ParseException
	 */
	@SuppressWarnings({ "deprecation", "unused" })
	private BooleanQuery setSearchAble(BooleanQuery booleanQuery)
			throws ParseException {
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		Term searchAllTerm = new Term("searchable", "0");
		Query searchAllQuery = new TermQuery(searchAllTerm);

		BooleanQuery booleanQueryUnit = new BooleanQuery();
		Term termUnitSearchable = new Term("searchable", "1");
		System.out.println(CastUtil.castString(session
				.getAttribute(FinalConfig.SESSION_HUMAN_UNIT_ID)));
		Term termUnitId = new Term("unitId", CastUtil.castString(session
				.getAttribute(FinalConfig.SESSION_HUMAN_UNIT_ID)));
		TermQuery unitTermQueryS = new TermQuery(termUnitSearchable);
		TermQuery unitTermQueryUnitId = new TermQuery(termUnitId);
		booleanQueryUnit.add(unitTermQueryS, Occur.MUST);
		booleanQueryUnit.add(unitTermQueryUnitId, Occur.MUST);
		BooleanQuery booleanQueryHumanIds = new BooleanQuery();
		Term humanIdsTermS = new Term("searchable", "2");
		Term humanIdsTermHumanId = new Term("humanIds", "*["
				+ CastUtil.castString(session
						.getAttribute(FinalConfig.SESSION_HUMANID)) + "]*");
		TermQuery humanIdQueryS = new TermQuery(humanIdsTermS);
		WildcardQuery humanIdsQuery = new WildcardQuery(humanIdsTermHumanId);

		booleanQueryHumanIds.add(humanIdQueryS, Occur.MUST);
		booleanQueryHumanIds.add(humanIdsQuery, Occur.MUST);
		BooleanQuery booleanQueryF=new BooleanQuery();
		booleanQueryF.add(searchAllQuery, Occur.SHOULD);
		booleanQueryF.add(booleanQueryUnit, Occur.SHOULD);
		booleanQueryF.add(booleanQueryHumanIds, Occur.SHOULD);
		booleanQuery.add(booleanQueryF,Occur.MUST);
		return booleanQuery;
	}
	
	private BooleanQuery setLwdw(BooleanQuery booleanQuery,PageLucene pageLucene){
		BooleanQuery lwdwQuery=new BooleanQuery();
		for (String lwdw : pageLucene.getLwdws()) {
			Term term=new Term("lwdw",lwdw);
			Query lwdw1=new TermQuery(term);
			lwdwQuery.add(lwdw1, Occur.SHOULD);
		}
		booleanQuery.add(lwdwQuery, Occur.MUST);
		return booleanQuery;
	}
	
	public PageLucene newPageBooleanSearch(PageLucene pageLucene)
			throws ParseException, IOException, InvalidTokenOffsetsException {
		BooleanQuery booleanQuery = new BooleanQuery();
		List<IndexFile> docFiles = new ArrayList<IndexFile>();
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		String[] fields = pageLucene.getFileSearchFields();
		BooleanClause.Occur[] flags = new BooleanClause.Occur[fields.length];
		for (int i = 0; i < flags.length; i++) {
			flags[i] = BooleanClause.Occur.SHOULD;
		}
		Query query;
		if(null!=pageLucene.getSearchText()&&!pageLucene.getSearchText().equals(""))
		{
			query = MultiFieldQueryParser.parse(pageLucene.getSearchText(), fields,
					flags, analyzer);
			booleanQuery.add(query, Occur.MUST);
		}
		if (!pageLucene.getIndexFrom().equals(FinalConfig.INDEX_FROM_ALL)) {
			Term term = new Term("indexFrom", pageLucene.getIndexFrom());
			Query termQuery = new TermQuery(term);
			booleanQuery.add(termQuery, Occur.MUST);
		}
//		
		if(pageLucene.getIslwdwSearch()){
			if(pageLucene.getMutilLwdw()){
				booleanQuery=setLwdw(booleanQuery, pageLucene);
			}else{
				Term term=new Term("lwdw",pageLucene.getLwdw());
				Query lwdwQuery=new TermQuery(term);
				booleanQuery.add(lwdwQuery, Occur.MUST);
			}
		}
		// 判断是否是需要在时间范围内查询，需要时间范围查询的话就需要使用组合查询BooleanQuery
		if (pageLucene.isBooleanQuery()) {
			NumericRangeQuery<Long> rangeQuery = NumericRangeQuery
					.newLongRange("date", pageLucene.getStartDate().getTime(),
							pageLucene.getEndDate().getTime(), true, true);
			booleanQuery.add(rangeQuery, Occur.MUST);
		}
		
		// 设置搜索文件的过滤，过滤掉不可搜索的文件
		booleanQuery = setSearchAble(booleanQuery);
		Sort sort = Sort.RELEVANCE;
		if(pageLucene.getOrderByTime()){
			sort=new Sort(new SortField("date",Type.LONG,true));
		}else{
			SortField[]  sortFields=new SortField[fields.length];
			for (int i=0;i<fields.length;i++) {
				sortFields[i]=new SortField(fields[i],Type.SCORE, false);
			}
			sort=new Sort(sortFields);
		}
		TopFieldCollector topFieldCollector = TopFieldCollector.create(sort,
				pageLucene.getCurrentPage() * pageLucene.getEveryPage(), false,
				false, false);
		is.search(booleanQuery, topFieldCollector);
		TopDocs hits = topFieldCollector.topDocs(
				(pageLucene.getCurrentPage() - 1) * pageLucene.getEveryPage(),
				pageLucene.getCurrentPage() * pageLucene.getEveryPage());
		QueryScorer scorer = new QueryScorer(booleanQuery);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				"<b><font color='red'>", "</font></b>");
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = is.doc(scoreDoc.doc);
			IndexFile docFile = doc2IndexFile(doc);
			String fileName = doc.get("fileName");
			String content = doc.get("content");
			// System.out.println(pageLucene.getIndexFrom()+"_"+doc.get("indexFrom"));
			String swbh = doc.get("swbh");
			String lwbh = doc.get("lwbh");
			if (null != swbh) {
				TokenStream tokenStream = analyzer.tokenStream("swbh",
						new StringReader(swbh));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, swbh);
				docFile.setSWBH(highlighterContent);
			}
			if (null != lwbh) {
				TokenStream tokenStream = analyzer.tokenStream("lwbh",
						new StringReader(lwbh));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, lwbh);
				if (null == highlighterContent) {
					docFile.setLWBH(lwbh);
				} else {
					docFile.setLWBH(highlighterContent);
				}
			}
			if (fileName != null) {
				TokenStream tokenStream = analyzer.tokenStream("fieldName",
						new StringReader(fileName));
				String highlighterFilename = highlighter.getBestFragment(
						tokenStream, fileName);
				if (null == highlighterFilename) {
					docFile.setFileName(fileName);
				} else {
					docFile.setFileName(highlighterFilename);
				}
			}
			if (content != null) {
				TokenStream tokenStream = analyzer.tokenStream("content",
						new StringReader(content));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, content);
				docFile.setContent(highlighterContent);
			}
			docFiles.add(docFile);

		}
		pageLucene.setTotalCount(topFieldCollector.getTotalHits());
		pageLucene.setResults(docFiles);
		pageLucene.initPageLucene();
		return pageLucene;
	}
	
	public PageLucene importantFileSearch(PageLucene pageLucene)
			throws ParseException, IOException, InvalidTokenOffsetsException {
		BooleanQuery booleanQuery = new BooleanQuery();
		List<IndexFile> docFiles = new ArrayList<IndexFile>();
		SmartChineseAnalyzer analyzer = new SmartChineseAnalyzer();
		String[] fields = pageLucene.getFileSearchFields();
		BooleanClause.Occur[] flags = new BooleanClause.Occur[fields.length];
		for (int i = 0; i < flags.length; i++) {
			flags[i] = BooleanClause.Occur.SHOULD;
		}
		Query query;
		if(null!=pageLucene.getSearchText()&&!pageLucene.getSearchText().equals(""))
		{
			query = MultiFieldQueryParser.parse(pageLucene.getSearchText(), fields,
					flags, analyzer);
			booleanQuery.add(query, Occur.MUST);
		}
		if (!pageLucene.getIndexFrom().equals(FinalConfig.INDEX_FROM_ALL)) {
			Term term = new Term("indexFrom", pageLucene.getIndexFrom());
			Query termQuery = new TermQuery(term);
			booleanQuery.add(termQuery, Occur.MUST);
		}
//		
		if(pageLucene.getIslwdwSearch()){
			if(pageLucene.getMutilLwdw()){
				booleanQuery=setLwdw(booleanQuery, pageLucene);
			}else{
				Term term=new Term("lwdw",pageLucene.getLwdw());
				Query lwdwQuery=new TermQuery(term);
				booleanQuery.add(lwdwQuery, Occur.MUST);
			}
		}
		// 判断是否是需要在时间范围内查询，需要时间范围查询的话就需要使用组合查询BooleanQuery
		if (pageLucene.isBooleanQuery()) {
			NumericRangeQuery<Long> rangeQuery = NumericRangeQuery
					.newLongRange("date", pageLucene.getStartDate().getTime(),
							pageLucene.getEndDate().getTime(), true, true);
			booleanQuery.add(rangeQuery, Occur.MUST);
		}
		
		// 设置搜索文件的过滤，过滤掉不可搜索的文件
		booleanQuery = setSearchAble(booleanQuery);
		Sort sort = Sort.RELEVANCE;
		if(pageLucene.getOrderByTime()){
			sort=new Sort(new SortField("date",Type.LONG,true));
		}
		TopFieldCollector topFieldCollector = TopFieldCollector.create(sort,
				pageLucene.getCurrentPage() * pageLucene.getEveryPage(), false,
				false, false);
		is.search(booleanQuery, topFieldCollector);
		TopDocs hits = topFieldCollector.topDocs(
				(pageLucene.getCurrentPage() - 1) * pageLucene.getEveryPage(),
				pageLucene.getCurrentPage() * pageLucene.getEveryPage());
		QueryScorer scorer = new QueryScorer(booleanQuery);
		Fragmenter fragmenter = new SimpleSpanFragmenter(scorer);
		SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter(
				"<b><font color='red'>", "</font></b>");
		Highlighter highlighter = new Highlighter(simpleHTMLFormatter, scorer);
		highlighter.setTextFragmenter(fragmenter);
		for (ScoreDoc scoreDoc : hits.scoreDocs) {
			Document doc = is.doc(scoreDoc.doc);
			IndexFile docFile = doc2IndexFile(doc);
			String fileName = doc.get("fileName");
			String content = doc.get("content");
			// System.out.println(pageLucene.getIndexFrom()+"_"+doc.get("indexFrom"));
			String swbh = doc.get("swbh");
			String lwbh = doc.get("lwbh");
			if (null != swbh) {
				TokenStream tokenStream = analyzer.tokenStream("swbh",
						new StringReader(swbh));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, swbh);
				docFile.setSWBH(highlighterContent);
			}
			if (null != lwbh) {
				TokenStream tokenStream = analyzer.tokenStream("lwbh",
						new StringReader(lwbh));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, lwbh);
				if (null == highlighterContent) {
					docFile.setLWBH(lwbh);
				} else {
					docFile.setLWBH(highlighterContent);
				}
			}
			if (fileName != null) {
				TokenStream tokenStream = analyzer.tokenStream("fieldName",
						new StringReader(fileName));
				String highlighterFilename = highlighter.getBestFragment(
						tokenStream, fileName);
				if (null == highlighterFilename) {
					docFile.setFileName(fileName);
				} else {
					docFile.setFileName(highlighterFilename);
				}
			}
			if (content != null) {
				TokenStream tokenStream = analyzer.tokenStream("content",
						new StringReader(content));
				String highlighterContent = highlighter.getBestFragment(
						tokenStream, content);
				docFile.setContent(highlighterContent);
			}
			docFiles.add(docFile);

		}
		pageLucene.setTotalCount(topFieldCollector.getTotalHits());
		pageLucene.setResults(docFiles);
		pageLucene.initPageLucene();
		return pageLucene;
	}
	public void close() throws IOException {
		reader.close();
	}

	private IndexFile doc2IndexFile(Document document) {
		IndexFile docFile = new IndexFile();
		docFile.setFileId(document.get("id"));
		docFile.setCreateTime(document.get("createTime"));
		docFile.setContent(document.get("content"));
		docFile.setIsImportantFile(document.get("isImportantFile"));
		String indexFrom = document.get("indexFrom");
		if (indexFrom != null ? indexFrom.equals(FinalConfig.INDEX_FORM_OA)
				: false) {
			docFile.setFileName(document.get("fileName"));
			docFile.setSWBH(document.get("swbh"));
			docFile.setLWBH(document.get("lwbh"));
			docFile.setLWDW(document.get("lwdw"));
			docFile.setIndexFrom(FinalConfig.INDEX_FORM_OA);
			docFile.setImageCssClass("file_pdf_ico_d32");
		} else {
			docFile.setHumanName(document.get("humanName"));
			docFile.setFilePath(document.get("path"));
			docFile.setImageCssClass(document.get("imageCssClass"));
			docFile.setIndexFrom(FinalConfig.INDEX_FORM_UPLOAD);
		}
		return docFile;
	}
}
